package com.csjbot.weedle_auto.app.automatic

import android.app.Activity
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.support.v7.app.AlertDialog
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import butterknife.bindView
import com.csjbot.weedle_auto.R
import com.csjbot.weedle_auto.SerialServer.util.bean.SerialPortEvents
import com.csjbot.weedle_auto.SerialServer.util.bean.SerialPortExceptionListener
import com.csjbot.weedle_auto.Slam.events.ConnectedEvent
import com.csjbot.weedle_auto.Slam.events.ConnectionLostEvent
import com.csjbot.weedle_auto.Slam.events.RobotStatusUpdateEvent
import com.csjbot.weedle_auto.adapter.MainAdapter
import com.csjbot.weedle_auto.app.BaseApplication
import com.csjbot.weedle_auto.app.automatic.bean.MainItemBean
import com.csjbot.weedle_auto.base.BaseActivity
import com.csjbot.weedle_auto.file.SaveFileStationListener
import com.csjbot.weedle_auto.file.constants_util.FileUtil
import com.csjbot.weedle_auto.serialport_util.SerialPortUtil
import com.csjbot.weedle_auto.util.CharactersUtil
import com.csjbot.weedle_auto.util.CheckConstants
import com.csjbot.weedle_auto.util.Csjlogger
import com.csjbot.weedle_auto.view.BaseDialog
import com.csjbot.weedle_auto.view.CustomTitleBar
import com.google.common.base.Preconditions.checkNotNull
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.IOException
import java.security.InvalidParameterException

/**
 * author : chenqi.
 * e_mail : 1650699704@163.com.
 * create_time : 8/21/17.
 */

class AutoMaticActivity : BaseActivity(), AutoMaticContract.view, SerialPortExceptionListener {


    private val listView: ListView by bindView(R.id.listView)
    val ct: CustomTitleBar by bindView(R.id.ct)
    private val testTimes: Button by bindView(R.id.test_times)
    val action: Button by bindView(R.id.action)
    val clear: Button by bindView(R.id.clear)

    private var bt = 0
    private var pt = ""

    private var presenter: AutoMaticContract.presenter? = null
    private var adapter: MainAdapter? = null
    private var fileFormat: String? = null//记录文件格式

    override val resureID: Int
        get() = R.layout.activity_main

    override fun initView() {
        SerialPortUtil.setSerialPortExceptionListener(this)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        presenter = MainPresenter(this, this)
        presenter!!.setList()
        initBar()
        onClick()
        super.initView()
    }

    override fun onResume() {
        super.onResume()
        val path = "/dev/ttyS4"//路径
        val backdate = 115200//波特率
        BaseApplication.instance.serial.openSerialPort(backdate, path)
    }

    fun onClick() {
        testTimes.setOnClickListener { timeDialog() }
        action.setOnClickListener { presenter!!.actionTask() }
        clear.setOnClickListener { presenter!!.clear() }
    }

    fun timeDialog() {
        val builder = BaseDialog.Builder(this)
        val view = View.inflate(this, R.layout.test_times, null)
        val times = view.findViewById(R.id.times) as EditText
        builder.setTitle("请输入测试次数！")
        builder.setContentView(view)
        builder.setNegativeButton("确认！", listener = DialogInterface.OnClickListener { dialog, _ ->
            var text = times.text.toString()
            if (text != "") {
                presenter!!.testTimes(Integer.parseInt(text))
            }
            dialog.dismiss()
        })

        builder.setPositiveButton("取消！", listener = DialogInterface.OnClickListener { dialog, _ -> dialog.dismiss() })
        val baseDialog = builder.create()
        baseDialog.show()
    }


    private val datas = arrayOf("设置串口号")

    private fun initBar() {
        ct.setOnTitleClickListener(object : CustomTitleBar.TitleOnClickListener {
            override fun onLeftClick() {}

            override fun onRightClick() {
                // TODO: 2016/5/17 构建一个popupwindow的布局
                val popupView = layoutInflater.inflate(R.layout.popupwindow, null)
                // TODO: 2016/5/17 为了演示效果，简单的设置了一些数据，实际中大家自己设置数据即可，相信大家都会。
                val lsvMore = popupView.findViewById(R.id.lsvMore) as ListView
                lsvMore.adapter = ArrayAdapter(this@AutoMaticActivity, android.R.layout.simple_list_item_1, datas)

                // TODO: 2016/5/17 创建PopupWindow对象，指定宽度和高度
                val window = PopupWindow(popupView, 200, 220)
                // TODO: 2016/5/17 设置动画
                window.animationStyle = R.style.popup_window_anim
                // TODO: 2016/5/17 设置背景颜色
                window.setBackgroundDrawable(ColorDrawable(Color.parseColor("#F8F8F8")))
                // TODO: 2016/5/17 设置可以获取焦点
                window.isFocusable = true
                // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
                window.isOutsideTouchable = true
                // TODO：更新popupwindow的状态
                window.update()
                val windowManager = windowManager
                val dm = DisplayMetrics()
                windowManager.defaultDisplay.getMetrics(dm)
                val SCREENWIDTH = dm.widthPixels
                window.showAsDropDown(ct, SCREENWIDTH, 0)
                lsvMore.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                    Csjlogger.info("chenqi item lsvmore " + position)
                    dialogADDPort()
                }
            }
        })
    }

    override fun onStop() {
        super.onStop()

    }

    private fun dialogADDPort() {
        val dialog1 = AlertDialog.Builder(this)
        val contentView1 = LayoutInflater.from(this).inflate(R.layout.serial_dialog, null)
        dialog1.setView(contentView1)
        dialog1.setTitle("选择串口")

        val add = contentView1.findViewById(R.id.add) as Button
        val port = contentView1.findViewById(R.id.spinner1) as Spinner
        val path = contentView1.findViewById(R.id.spinner2) as Spinner

        port.setSelection(1, true)
        path.setSelection(1, true)
        /**
         * 默认选中
         */
        bt = Integer.parseInt(resources.getStringArray(R.array.btv)[1])
        pt = resources.getStringArray(R.array.path)[1]

        val alertDialog = dialog1.create()
        alertDialog.setCanceledOnTouchOutside(true)
        alertDialog.show()

        port.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                bt = Integer.parseInt(resources.getStringArray(R.array.btv)[position])
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }

        path.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                pt = resources.getStringArray(R.array.path)[position]
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }

        add.setOnClickListener {
            BaseApplication.instance.serial.openSerialPort(bt, pt)
            alertDialog.dismiss()
        }
    }


    override fun onRestart() {
        super.onRestart()
    }

    override fun onStart() {
        super.onStart()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnEventMainThread(event: SerialPortEvents) {
        presenter!!.setSerialInfor(event, 3)
    }

    override fun setPresenter(presenter: AutoMaticContract.presenter) {
        this.presenter = checkNotNull(presenter)
    }

    override fun showList(list: List<MainItemBean>) {
        adapter = MainAdapter(this, this)
        listView.adapter = adapter
        adapter!!.notifyDataSetChanged()
    }

    override fun testStop(tag: String) {
        runOnUiThread {
            Toast.makeText(this@AutoMaticActivity, "测试完毕！", 1000).show()
            presenter!!.getResult()
        }
    }

    override fun stopShowActionButton() {
        action.isClickable = false

    }

    override fun openShowActionButton() {
        action.isClickable = true
    }

    override fun updateTouch(msg: String, s: Boolean) {
        Csjlogger.info("chenqi ManualFragment tuch{}" + msg)
        adapter!!.updata(1, listView, msg, s)
    }

    override fun updateOther(serialPort: String, s: Boolean) {
        adapter!!.updata(0, listView, serialPort, s)
    }

    override fun updateSnUp(msg: String, s: Boolean) {
        Csjlogger.info("chenqi ManualFragment up{}" + msg)
        adapter!!.updata(2, listView, msg, s)
    }

    override fun updateSnDown(msg: String, s: Boolean) {
        Csjlogger.info("chenqi ManualFragment down{}" + msg)
        adapter!!.updata(3, listView, msg, s)
    }

    override fun showResult(msg: String) {
        Csjlogger.info("chenqi showResult{}" + msg)
        showSavePath(msg)
        presenter!!.closeTask()
    }

    /**
     * listView
     */
    private fun showSavePath(msg: String) {
        val view = View.inflate(this, R.layout.file_format_dialog, null)
        val textView = view.findViewById(R.id.path_name) as TextView
        val editText = view.findViewById(R.id.path_name_enter) as EditText
        val spinner = view.findViewById(R.id.file_name_ge) as Spinner
        val textView1 = view.findViewById(R.id.msg) as TextView
        val builder = BaseDialog.Builder(this)
        builder.setTitle(R.string.is_not_save_file)

        textView1.text = msg
        textView.text = getString(R.string.file_path_is) + CheckConstants.path.toString()

        builder.setCancleEnable(false)
        builder.setContentView(view)

        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                fileFormat = resources.getStringArray(R.array.file)[position]
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }

        builder.setNegativeButton(R.string.save, listener = DialogInterface.OnClickListener { dialog, _ ->
            //文件名字
            var fileName = editText.text.toString()
            //如果在相应
            if (fileName.equals(getString(R.string.enter_file_name), ignoreCase = true)) {
                fileName = CharactersUtil.randomChar.toString()
            }

            fileName += fileFormat!!

            Csjlogger.info("chenqi filename {}{}{}" + fileName + CheckConstants.path + msg)

            //文件格式
            FileUtil.saveFileToSave(fileName, CheckConstants.path, msg, object : SaveFileStationListener {
                override fun FileNotFound() {
                    Toast.makeText(this@AutoMaticActivity, R.string.save_failed, 1000)
                    dialog.dismiss()
                }

                override fun IOEError() {
                    Toast.makeText(this@AutoMaticActivity, R.string.save_failed, 1000)
                    dialog.dismiss()
                }

                override fun SaveSuccess() {
                    Toast.makeText(this@AutoMaticActivity, R.string.save_success, 1000)
                    dialog.dismiss()
                }

                override fun FileIsExists() {
                    Toast.makeText(this@AutoMaticActivity, R.string.file_exists, 1000)
                    dialog.dismiss()
                }
            })
            closeIMM(view)
        })

        builder.setPositiveButton(getString(R.string.not_save), listener = DialogInterface.OnClickListener { dialog, _ ->
            dialog.dismiss()
        })
        val dialog = builder.create()
        dialog.show()
    }

    override fun showSlamStatus(msg: String, s: Boolean) {
        Csjlogger.info("chenqi auto accc{}" + msg)
        adapter!!.updata(4, listView, msg, s)
    }

    override fun clearResult() {
        adapter!!.updata(listView)
    }

    override fun slamLost() {
        runOnUiThread { Toast.makeText(this@AutoMaticActivity, "slam断开连接了", 1000).show() }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    /**
     * 添加一个
     *
     * @param event 2017年4月12日 添加了充电显示的功能
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnEventMainThread(event: ConnectionLostEvent) {
        event.error
        presenter!!.connectLostSlam()
    }

    /**
     * 添加一个
     *
     * @param event 2017年4月12日 添加了充电显示的功能
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnEventMainThread(event: RobotStatusUpdateEvent) {
        event.batteryPercentage
        presenter!!.slamStatus(event)
    }

    /**
     * 添加一个
     *
     * @param event 2017年4月12日 添加了充电显示的功能
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnEventMainThread(event: ConnectedEvent) {
        presenter!!.connectSlam()
    }

    override fun ioException(e: IOException) {
        Csjlogger.debug("start SerialPortUtil ioException")
        Toast.makeText(this@AutoMaticActivity, "串口未知错误请重新发送消息！", 2000).show()
    }

    override fun invalidException(e: InvalidParameterException) {
        Csjlogger.debug("start SerialPortUtil ioException")
        Toast.makeText(this@AutoMaticActivity, "请配置你的端口！", 2000).show()
    }

    override fun securityException(e: SecurityException) {
        Csjlogger.debug("start SerialPortUtil ioException")
        toast("请检查你的设备是否有串口!", 2000)
    }

    override fun otherException(error: Boolean) {
        Csjlogger.debug("start SerialPortUtil ioException" +
                "")
        toast("未知错误，请检查你的设备是否有串口！", 2000)
    }

    private fun Activity.toast(message: String, length: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(this, message, length).show()
    }
}
